var express = require('express');
app = express(),
	images = require("images"),
	bodyParser = require('body-parser'),
	moment = require('moment'),
	async = require('async'),
	crypto = require('crypto'),
	path = require('path'),
	fs = require('fs'),
	config = require('config'),
	multer = require('multer'),
	upload = multer({dest: 'uploadTemp/'}).any();


app.use(bodyParser.json({limit: '5mb'}));
app.use('/uploads',express.static(path.join(__dirname,'uploads')));
app.get('/', function (req, res) {
	res.jsonp("ok");
});
// respond with "hello world" when a GET request is made to the homepage
app.post('/api/upload/img', function (req, res) {
	var base64 = req.body.imgbase64;
	saveImg(base64, function (err, picPath, orPicSize) {
		if (err) {
			console.log(err);
			var result = {flagCode: 0, message: '出错了'};
			if (err.message) {
				result.message = err.message;
			}
			return res.status(200).send(result);
		} else {
			return res.status(200).send({
				flagCode: 1,
				result: {
					picPath: picPath,
					orPicSize: orPicSize
				}
			});
		}

	});
});

app.post('/api/upload/wangedit', function (req, res) {
	upload(req, res, function (err) {
		if (err) {
			console.log(err);
			return res.status(200).send({
				errno: -1,
				data: []
			});
		} else {

			if (!req.files || (req.files && req.files.length <= 0)) {
				return res.status(200).send({
					errno: -1,
					data: []
				});
			}
			var base64Data = null,temp = null;
			for (var i = 0; i < req.files.length; i++) {
				fs.readFile(req.files[i].path,function(err,data){
					if(err){
					console.log(err);
					}else{
						base64Data = new Buffer(data).toString('base64')
						saveImg(base64Data, function (err, picPath, orPicSize) {
							if (err) {
								console.log(err);
								return res.status(200).send({
									errno: '-1',
									data: []
								});
							} else {
								return res.status(200).send({
									errno: "0",
									data: [
										picPath
									]
								});
							}

						});
					}
				})

			}
		}


	});


})

var server = app.listen(3000, function () {
	var host = server.address().address;
	var port = server.address().port;

	console.log('Example app listening at http://%s:%s', host, port);
});

/**
 * 保存图片
 * @param imgBase64 传入的base64
 * @param cb(err,picPath,smallPicPath)  回调方法，返回图片地址
 */
function saveImg(imgBase64, cb) {
	var waterFall = [
		function (done) {
			crypto.randomBytes(8, function (err, buffer) {
				var token = buffer.toString('hex');
				done(err, token);
			})
		},
		function (token, done) {
			var dataBuffer = new Buffer(imgBase64, 'base64');
			var year = moment().format("YYYY");
			var month = moment().format("MM");
			var day = moment().format("DD");
			var fullDir = config.uploads.imgUpload.dest + year + '/' + month + '/' + day + '/';
			console.log("fullDir", fullDir);
			//创建文件夹
			//logger.logDebug("path.resolve(process.cwd(),'.'+fullDir):", path.resolve(process.cwd(), '.' + fullDir));
			if (!mkdirsSync(path.resolve(fullDir))) {
				console.info('mkdirsSync false.');
				return done(new Error("mkdirsSync false"));
			}
			var picPath = fullDir + token + '.jpg';
			// var smallPicPath = fullDir + token + '_100.jpg';
			var orWidth = images(dataBuffer).width(); //原件宽度大小
			var orHeight = images(dataBuffer).height(); //原件高度大小
			console.info(picPath);
			var orPicSize = {
				width: orWidth,
				height: orHeight
			};
			// var smallPicSize = {
			//     width: orWidth,
			//     height: orHeight
			// };
			var compressQuality = 50;
			if (dataBuffer.length / 1024 <= 200) { //如果图片质量小余或等于200kb就不压缩
				compressQuality = 80;
			}
			// images(dataBuffer)
			//     .save(path.resolve('.' + smallPicPath), 'jpg', { //保存图片到文件,图片质量为50
			//         quality: compressQuality
			//     });
			images(dataBuffer)
				.save(path.resolve(picPath), 'jpg', { //保存图片到文件,图片质量为50
					quality: compressQuality
				});

			// done(null, picPath, smallPicPath, orPicSize, smallPicSize);
			done(null, picPath, orPicSize);
		}
	];
	async.waterfall(waterFall, function (err, picPath, orPicSize) {
		cb(err, picPath, orPicSize);
	});
}

//创建多层文件夹 同步
function mkdirsSync(dirpath) {
	console.log('dirpath:', dirpath);
	if (!fs.existsSync(dirpath)) {
		var pathtmp;
		var isRootPath = false;
		if (dirpath.indexOf(path.sep) == 0) {
			isRootPath = true;
		}
		dirpath.split(path.sep).forEach(function (dirname) {
			if (pathtmp) {
				pathtmp = path.join(pathtmp, dirname);
			} else {
				pathtmp = isRootPath ? path.sep + dirname : dirname;
			}
			if (pathtmp.length > 0) {
				if (!fs.existsSync(pathtmp)) {
					if (!fs.mkdirSync(pathtmp)) {
						return false;
					}
				}
			}

		});
	}
	return true;
}